<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="RolesList">
              <!-- type:index会自动生成序号 -->
              <!-- 当el-table元素中注入data对象数组后，在el-table-column中用prop属性来对应对象中的键名即可填入数据，用label属性来定义表格的列名。可以使用width属性来定义列宽。 -->
              <el-table-column label="序号" width="50" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述详情" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button type="success" @click="showDialogAssign=true">分配权限</el-button>
                  <el-button size="mini" type="primary" @click="hEdit(row.id)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="hdelRoles(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit?'编辑':'添加'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="resetForm"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogAssign"
      >
        <assignPermission />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoles, addRoles, delRoles, getRolesDetail, updateRoles } from '@/api/settings'
import assignPermission from './assignPermission.vue'
export default {
  components: { assignPermission },
  data() {
    return {
      showDialogAssign: false, // 分配弹层的隐藏
      isEdit: false,
      showDialog: false, // 隐藏添加框
      // 变单数据
      roleForm: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '请输入内容', trigger: 'blur' }, { min: 2, max: 10, message: '请输入1到10位的名字', trigger: 'blur' }],
        description: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },

      // 角色列表
      RolesList: [],

      // pageParams
      pageParams: {
        page: 1, // 每页
        pagesize: 2// 每页条数
      },
      // 总条数
      total: 0
    }
  },
  created() {
    // 页面加载时获取角色列表
    this.loadRoles()
  },
  methods: {
    //
    resetForm() {
      this.$refs.roleForm.resetFields()
    },
    //
    async loadRolesDetail(id) {
      try {
        const res = await getRolesDetail(id)
        if (res.code === 10000) {
          this.roleForm = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    //
    hEdit(id) {
      this.showDialog = true
      this.isEdit = true // 编辑状态
      this.loadRolesDetail(id)
    },
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 删除
    hdelRoles(id) {
      this.$confirm('确定删除').then(async() => {
        const res = await delRoles(id)
        console.log('delRoles', res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.pageParams.length === 1) {
          this.pageParams--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 重新渲染
        this.loadRoles()
      }).catch((error) => {
        console.log(error)
      })
    },
    // 新增
    async hAddRoles() {
      try {
        const res = await addRoles(this.roleForm)
        if (res.code !== 10000) { return this.$message.error(res.message) }
        this.$message.success(res.message)
        // 因为ajax是异步的
        this.total++
        //
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        this.pageParams.page = maxPage
        // 重新渲染
        this.loadRoles()
      } catch (error) {
        console.log('')
      }
    },
    //
    async doEdit() {
      try {
        const res = await updateRoles(this.roleForm)
        if (res.code !== 10000) return this.$message.error('失败')
        this.$message.success('成功')
        //
        this.loadRoles()
        //
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },

    // 弹窗确定框
    hSubmit() {
      // 点了提交,调用新增的封装组件
      this.$refs.roleForm.validate((vaild) => {
        if (!vaild) return this.$message.error('失败')
        this.$message.success('成功')
        // 做具体的添加动作
        // this.hAddRoles()
        //
        this.showDialog = false
        //
        this.isEdit ? this.doEdit() : this.hAddRoles()
        console.log(this.isEdit ? this.doEdit() : this.hAddRoles())
      })
    },
    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.pagesize = val
      // 重新渲染
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = 1
      this.pageParams.page = val
      // 重新渲染
      this.loadRoles()
    },

    async loadRoles() {
      try {
        /*    try {

        } catch (error) {

        } 的作用是,报错,不会使程序崩溃
        */
        const res = await getRoles(this.pageParams)
        // console.log('loadRoles', res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.RolesList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(new Error(''))
      }
    }
  }
}
</script>
